<template>
  <el-card shadow="always">
    <el-row :gutter="20">
      <el-col :span="4" class="head">
        <el-input
          v-model="roleQuery.roleName"
          placeholder="请输入角色名"
          clearable
        ></el-input>
      </el-col>
      <el-button type="primary" @click="handleSearch" :icon="Search"
        >搜索</el-button
      >
      <el-button type="warning" :icon="Delete" @click="handleEmpty"
        >清空</el-button
      >
    </el-row>
    <el-divider />
    <el-row :gutter="20" style="margin: 15px 0px">
      <el-button type="primary" size="default" @click="handlerRoleDialog()"
        >添加角色</el-button
      >
      <el-button type="danger" size="default" @click="deleteSelectRoles"
        >批量删除</el-button
      >
    </el-row>

    <el-table
      ref="multipleTableRef"
      :data="tableData"
      style="width: 100%; margin-bottom: 15px"
      border
      v-loading="loading"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="40" />
      <el-table-column type="index" label="序号" width="55" align="center" />
      <el-table-column
        v-for="(option, index) in options"
        :key="index"
        :label="option.label"
        :prop="option.prop"
        :width="option.width"
        align="center"
      >
        <template #default="{ row }" v-if="option.label === 'manipulate'">
          <el-button
            type="info"
            size="small"
            :icon="Menu"
            title="分配菜单"
            @click="distributeMenu(row)"
          ></el-button>
          <el-button
            type="warning"
            size="small"
            :icon="Edit"
            title="编辑角色"
            @click="handlerRoleDialog(row)"
          ></el-button>
          <el-popconfirm
            title="Are you sure to delete this?"
            @confirm="deleteRole(row)"
          >
            <template #reference>
              <el-button
                type="danger"
                size="small"
                :icon="Delete"
                title="删除角色"
              ></el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      v-model:currentPage="roleQuery.pageNo"
      v-model:page-size="roleQuery.pageSize"
      :page-sizes="[2, 10, 50]"
      layout=" prev, pager, next, jumper,->,sizes,total"
      :total="roleQuery.total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      style="text-align: right"
    />
  </el-card>
  <RoleDialog
    v-model="roleDialogVisible"
    v-if="roleDialogVisible"
    :roleDialogTitle="roleDialogTitle"
    :roleDialogValue="roleDialogValue"
    @initTableList="initTableList"
  />
  <DistributeMenu
    v-model="distributeDialogVisible"
    v-if="distributeDialogVisible"
    :roleMenuList="roleMenuList"
    :selectRoleId="selectRoleId"
  />
</template>

<script setup>
import { Delete, Search, Edit, User, Menu } from '@element-plus/icons-vue'
import { ref } from 'vue'
import { options } from './options'
import {
  getRoleListByOption,
  deleteRoleByIds,
  getMenuListByRoleId
} from '@/api/authority.js'
import { ElMessage } from 'element-plus/lib/components'
import RoleDialog from './components/roleDialog.vue'
import DistributeMenu from './components/roleDistributeMenu.vue'
import { isNull } from '@/utils/filters.js'
import { ElMessageBox } from 'element-plus'
import { handleTokenExpire } from '@/utils/handleTokenExpire.js'

const selectRoleId = ref('')

const roleMenuList = ref([])

const distributeDialogVisible = ref(false)

const tableData = ref([])
const selectIds = ref([])

const roleDialogVisible = ref(false)
const initRoleQuery = () => {
  return {
    roleName: '',
    pageNo: 1,
    pageSize: 2,
    total: 0
  }
}

const roleDialogValue = ref({})

const roleDialogTitle = ref('')

const roleQuery = ref(initRoleQuery())

const loading = ref(true)
// const roleName = ref('')

const initTableList = async () => {
  try {
    const res = await getRoleListByOption(roleQuery.value)
    roleQuery.value.total = res.data.total
    tableData.value = res.data.records
    loading.value = false
    // console.log(res)
  } catch (error) {
    handleTokenExpire(error)
  }
}

initTableList()

const handleSizeChange = (size) => {
  roleQuery.value.pageSize = size
  roleQuery.value.pageNo = 1
  initTableList()
}
const handleCurrentChange = (currentPage) => {
  roleQuery.value.pageNo = currentPage
  initTableList()
}

const handleSearch = () => {
  initTableList(roleQuery.value)
}

const handleEmpty = () => {
  roleQuery.value = initRoleQuery()

  initTableList(roleQuery.value)
}

const handlerRoleDialog = (row) => {
  if (isNull(row)) {
    roleDialogTitle.value = '添加角色'
  } else {
    roleDialogTitle.value = '编辑角色'
    const rdv = {
      roleName: row.roleName,
      roleRemark: row.roleRemark,
      id: row.id
    }
    roleDialogValue.value = JSON.parse(JSON.stringify(rdv))
  }
  roleDialogVisible.value = true
}

const deleteRole = async (row) => {
  // console.log(row)
  const roleId = [row.id]
  try {
    await deleteRoleByIds(roleId)
    ElMessage({
      type: 'success',
      duration: 1500,
      message: '删除成功'
    })
    initTableList()
  } catch (error) {
    ElMessage({
      type: 'error',
      duration: 1500,
      message: error
    })
  }
}

const handleSelectionChange = (select) => {
  const selectList = JSON.parse(JSON.stringify(select))
  selectIds.value = selectList.map((item) => item.id)
}

const deleteSelectRoles = () => {
  ElMessageBox.confirm(
    'proxy will permanently delete select roles. Continue?',
    'Warning',
    {
      confirmButtonText: 'OK',
      cancelButtonText: 'Cancel',
      type: 'warning'
    }
  )
    .then(async () => {
      const roleIds = selectIds.value
      await deleteRoleByIds(roleIds)
      initTableList()
      ElMessage({
        type: 'success',
        message: 'Delete completed'
      })
    })
    .catch((error) => {
      ElMessage({
        type: 'info',
        message: error
      })
    })
}

const distributeMenu = async (row) => {
  try {
    const roleMenuLists = await getMenuListByRoleId(row.id)
    roleMenuList.value = roleMenuLists.data.childrenMenuList
    selectRoleId.value = row.id
    /* [{…}, {…}] */
    // console.log(roleMenuLists.data.childrenMenuList)
  } catch (error) {
    ElMessage({
      type: 'error',
      duration: 1500,
      message: error
    })
  }
  distributeDialogVisible.value = true
}
</script>

<style lang="scss" scoped>
.head {
  margin-right: 10px;
}
</style>
